
package com.kweative.lingua.server.client;

import com.kweative.lingua.server.request.RequestHandler;
import com.kweative.lingua.server.response.ResponseHandler;
import com.kweative.network.Response;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author henrik
 */
public class SocketClient extends Client {
    private Socket socket;

    public SocketClient(RequestHandler request, ResponseHandler response,Socket socket) throws IOException {
        super(request,response,socket.getInputStream(),socket.getOutputStream());
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            if (getRequest().isPersistent())
                socket.setKeepAlive(true);
            socket.setSoTimeout(getRequest().getTimeout());
        } catch (SocketException ex) {
            Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE,"Timeout failed", ex);
        }
        while(socket.isConnected()) {
            try {
                super.read();
            } catch(SocketTimeoutException ex) {
                break;
            } catch (Throwable ex) {
                Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE, null, ex);
                break;
            }
            getRequest().clear();
            getResponse().clear();
        }
        try {
            socket.close();
        } catch (IOException ex) {
            Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


}
